<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

  <button>按钮</button>

  <input type="text">
  <button class="cancel">取消</button>
  
  <!-- CDN引入: 网络的js文件 -->
  <!-- <script src="https://cdn.jsdelivr.net/npm/underscore@1.13.4/underscore-umd-min.js"></script> -->
  <!-- 本地引入: 下载js文件, 并且本地引入 -->
  <script src="./js/underscore.js"></script>

  <script>
    function hythrottle(fn, interval, { leading = true, trailing = false } = {}) {
      let startTime = 0
      let timer = null

      const _throttle = function(...args) {
        return new Promise((resolve, reject) => {
          try {
             // 1.获取当前时间
            const nowTime = new Date().getTime()

            // 对立即执行进行控制
            if (!leading && startTime === 0) {
              startTime = nowTime
            }

            // 2.计算需要等待的时间执行函数
            const waitTime = interval - (nowTime - startTime)
            if (waitTime <= 0) {
              // console.log("执行操作fn")
              if (timer) clearTimeout(timer)
              const res = fn.apply(this, args)
              resolve(res)
              startTime = nowTime
              timer = null
              return
            } 

            // 3.判断是否需要执行尾部
            if (trailing && !timer) {
              timer = setTimeout(() => {
                // console.log("执行timer")
                const res = fn.apply(this, args)
                resolve(res)
                startTime = new Date().getTime()
                timer = null
              }, waitTime);
            }
          } catch (error) {
            reject(error)
          }
        })
      }

      _throttle.cancel = function() {
        if (timer) clearTimeout(timer)
        startTime = 0
        timer = null
      }

      return _throttle
    }
  </script>

  <script>
    // 1.获取input元素
    const inputEl = document.querySelector("input")
    const cancelBtn = document.querySelector(".cancel")

    // 2.underscore节流处理代码
    // let counter = 1
    // inputEl.oninput = _.throttle(function() {
    //   console.log(`发送网络请求${counter++}:`, this.value)
    // }, 1000)

    // 3.自己实现的节流函数
    let counter = 1

    const throttleFn = hythrottle(function(event) {
      console.log(`发送网络请求${counter++}:`, this.value, event)
      return "throttle return value"
    }, 3000, { trailing: true })

    throttleFn("aaaa").then(res => {
      console.log("res:", res)
    })

  </script>

</body>
</html>